<template>
  <div class="grad-coupon-wrap">
    <div class="grad-title">{{ prop.title }}</div>
    <el-form
      ref="gradFormRef"
      :model="ruleForm"
      :rules="prop.rules"
      :label-width="prop.labelWidth"
      class="edit-form-wrap"
    >
      <el-form-item :label="prop.items.label" :prop="prop.items.prop">
        <el-input
          v-model.trim="ruleForm[prop.items.prop]"
          :placeholder="prop.items.placeholder"
          maxlength="30"
          clearable
        >
          <template #append>{{ prop.items.unit }}</template>
        </el-input>
      </el-form-item>
    </el-form>
    <ComCoupon
      ref="comCouponRef"
      :activityId="prop.activityId"
      :postList="false"
      :couponsList="prop.couponsList"
      :labelWidth="80"
    ></ComCoupon>
  </div>
</template>

<script lang="ts" setup>
import ComCoupon from './comCoupon.vue';
interface Props {
  activityId?: string | any;
  labelWidth?: string;
  title?: string; // 标题  一级配置
  level?: string;
  items: any;
  rules: any;
  couponsList: any;
}
const prop = withDefaults(defineProps<Props>(), {
  activityId: '',
  labelWidth: '80px',
  title: '一级配置',
  level: '0',
  items: {} as any,
  rules: [] as any,
  couponsList: [] as any,
});

const gradFormRef = ref();
const comCouponRef = ref();

const ruleForm: any = reactive({});

const getData = async (levelStr: string) => {
  if (!gradFormRef.value) return;
  let flag = true;
  let objError = {} as any;
  let comData = [] as any;
  try {
    comData = await Promise.all([
      gradFormRef.value.validate((e: any, fields: any) => {
        flag = flag ? e : false;
        if (!e) {
          objError = { ...objError, ...fields };
        }
      }),
      comCouponRef.value?.getData(),
    ]);
  } catch (e) {}
  if (!flag || !comData[1]) {
    for (const key in ruleForm) {
      if (objError[key]) {
        gradFormRef.value.scrollToField(key);
        break;
      }
    }
    return false;
  }

  const arr = [] as any;
  comData[1].forEach((item: any) => {
    item[prop.items.prop] = ruleForm[prop.items.prop];
    if (prop.level) {
      item.level = prop.level;
    }
    if (levelStr) {
      item.level = levelStr;
    }
    arr.push(item);
  });
  return arr;
};

const setData = (data: any) => {
  console.log('ddd---', data);
  ruleForm[prop.items.prop] = data[0][prop.items.prop];
  comCouponRef.value?.setData(data);
};

defineExpose({
  getData,
  setData,
});
</script>

<style lang="scss">
.grad-coupon-wrap {
  width: 618px;
  margin: 0px 48px 20px 48px;
  border: 1px solid #c4c4c4;
  border-radius: 8px;

  .grad-title {
    margin: 8px;
    line-height: 22px;
    font-size: 13px;
    color: #000;
  }
}
</style>